package com.wyl.config;

import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.Ordered;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.DateFormatterRegistrar;
import org.springframework.format.number.NumberFormatAnnotationFormatterFactory;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
import org.thymeleaf.extras.tiles2.dialect.TilesDialect;
import org.thymeleaf.extras.tiles2.spring4.web.configurer.ThymeleafTilesConfigurer;
import org.thymeleaf.extras.tiles2.spring4.web.view.ThymeleafTilesView;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolver;
import org.thymeleaf.templateresolver.UrlTemplateResolver;

import com.wyl.interceptor.PageLinkInterceptor;
import com.wyl.interceptor.TokenInterceptor;
import com.wyl.search.bean.SearchMessageBean;

import nz.net.ultraq.thymeleaf.LayoutDialect;

/**
 * 会扫描spring的注释类。这个类，将 只查找Controller 类并将其加到spring容器里。
  * @ClassName: WebMvcConfig
  * @Description: TODO
  * @author sunkxu
  * @date 2014年6月6日 上午10:34:13
 */
@Configuration
class WebMvcConfig extends WebMvcConfigurerAdapter {
	
	

    private static final String MESSAGE_SOURCE = "/WEB-INF/i18n/messages";
    private static final String VIEWS = "/WEB-INF/views/";

    private static final String RESOURCES_HANDLER = "/resources/";
    private static final String RESOURCES_LOCATION = RESOURCES_HANDLER + "**";


    
    @Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/login").setViewName("login");
		registry.addViewController("/access").setViewName("access");
		registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
	}
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	registry.addInterceptor(new TokenInterceptor());
    	registry.addInterceptor(new PageLinkInterceptor());    	
    }


    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource());
        return validator;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(RESOURCES_HANDLER).addResourceLocations(RESOURCES_LOCATION);
    }

/*    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }*/
        
    /*
     * 添加日期格式处理类
      * <p>Title: mvcConversionService</p>
      * <p>Description: </p>
      * @return
      * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#mvcConversionService()
     */
    
    @Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());		
		DateFormatterRegistrar dateFormatterRegistrar = new DateFormatterRegistrar();	
		dateFormatterRegistrar.setFormatter(new DateFormatter("yyyy-MM-dd HH:mm"));
		dateFormatterRegistrar.registerFormatters(registry);
	}
	
	
    @Bean
	public FilterRegistrationBean hiddenFilterRegistrationBean() {
		return new FilterRegistrationBean(new HiddenHttpMethodFilter());
	}
    
    /**
     * 设置多国语言
      * @Title: messageSource
      * @Description: TODO
      * @param @return    设定文件
      * @return MessageSource    返回类型
      * @throws
     */
    @Bean(name = "messageSource")
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename(MESSAGE_SOURCE);
        messageSource.setCacheSeconds(5);
        return messageSource;
    }

     /**
      * 设置spring前台用模板，位置和命名方式，字符编码等
       * @Title: templateResolver
       * @Description: TODO
       * @param @return    设定文件
       * @return TemplateResolver    返回类型
       * @throws
      */
    @Bean
    public TemplateResolver templateResolver() {
        TemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setPrefix(VIEWS);
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        //add by sunk.xu
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setCacheable(false);
        return templateResolver;
    }
    
    /**
     * 未知
      * @Title: urlTemplateResolver
      * @Description: TODO
      * @param @return    设定文件
      * @return UrlTemplateResolver    返回类型
      * @throws
     */
    @Bean
    public UrlTemplateResolver urlTemplateResolver() {
        return new UrlTemplateResolver();
    }

    /**
     * 设置spring 模板
      * @Title: templateEngine
      * @Description: TODO
      * @param @return    设定文件
      * @return SpringTemplateEngine    返回类型
      * @throws
     */
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.addTemplateResolver(templateResolver());
        templateEngine.addTemplateResolver(urlTemplateResolver());
        templateEngine.addDialect(new SpringSecurityDialect());
        templateEngine.addDialect(new TilesDialect());
        templateEngine.addDialect(new LayoutDialect());
        return templateEngine;
    }

    /**
     *  Handles all views except for the ones that are handled by Tiles. This view resolver
     *  will be executed as first one by Spring.
     */
    @Bean   
    public ViewResolver thymeleafViewResolver() {
        ThymeleafViewResolver vr = new ThymeleafViewResolver();
        vr.setTemplateEngine(templateEngine());
        vr.setCharacterEncoding("UTF-8");
        vr.setOrder(Ordered.HIGHEST_PRECEDENCE);
        // all message/* views will not be handled by this resolver as they are Tiles views
        //vr.setExcludedViewNames(new String[]{"message/*"});
        return vr;
    }

    /**
     * Handles Tiles views.
     */
    @Bean
    public ViewResolver tilesViewResolver() {
        ThymeleafViewResolver vr = new ThymeleafViewResolver();
        vr.setTemplateEngine(templateEngine());
        vr.setViewClass(ThymeleafTilesView.class);
        vr.setCharacterEncoding("UTF-8");
        vr.setOrder(Ordered.LOWEST_PRECEDENCE);
        return vr;
    }

    @SuppressWarnings("deprecation")
	@Bean
    public ThymeleafTilesConfigurer tilesConfigurer() {
        ThymeleafTilesConfigurer ttc = new ThymeleafTilesConfigurer();
        ttc.setDefinitions(new String[]{"/WEB-INF/views/message/tiles-defs.xml"}); 
        return ttc;
    }

    
	/**
	  *　查询和和分页用
	  * @Title: searchMessageBean
	  * @Description: TODO
	  * @param @return    设定文件
	  * @return SearchMessageBean    返回类型
	  * @throws
	 */
	@Bean
	@Scope("prototype")
	public static SearchMessageBean searchMessageBean(){
		SearchMessageBean bean = new SearchMessageBean();
		return bean;
	}


}
